#include <QFile>
#include <QFileDialog>

#include "peer_node_server_role.h"
#include "logger.h"

PeerNodeServerRole::PeerNodeServerRole(QObject *parent, int port)
    :QTcpServer(parent)
{
    conn_socket = NULL;
    if(true == listen(QHostAddress::Any, port))
    {
        MYLOG("listen port %d", port);
    }
    else
    {
        MYLOG("listen port %d error", port);
        return;
    }
    connect(this, SIGNAL(newConnection()), this, SLOT(acceptFileConnection()));
}

PeerNodeServerRole::~PeerNodeServerRole()
{
    if(conn_socket != NULL)
        delete conn_socket;
}


//#len#filepath#
#define PAK_ERR "PKE"
#define FP_ERR  "FPE"
#define SUCC    "SUC"
void PeerNodeServerRole::connSockCheckdata()
{
     if(conn_socket->bytesAvailable() >= 11)
     {
         ///< 定义消息头11个字节,
         /// "#0000000011#G:/chat.sql#" ==> header "#0000000011",
         char buf[1024] = {0};
         conn_socket->read(buf,11);///读取11个字节,
         QString msg;

         if(buf[0] != '#')
         {
             msg = PAK_ERR;
             conn_socket->write(msg.toLatin1(), msg.length());
             return;
         }

         msg = buf;
         long len = msg.mid(1, 10).toLong();  /// "#0000000011#G:/chat.sql#" ==> header "#0000000011",  len = 11，
         conn_socket->read(buf,len + 2);

         msg = buf;
         QString filepath = msg.mid(1, len);///文件的全路径
         MYLOG("PeerNodeServerRole filepath : %s", filepath.toStdString().c_str());
         transfer(filepath);
     }
}

void PeerNodeServerRole::connSockDisconnected()
{
    MYLOG("connSockDisconnected !")
}

void PeerNodeServerRole::acceptFileConnection()
{
    QTcpSocket *client = this->nextPendingConnection();
    qintptr sockfd = client->socketDescriptor();
    qDebug() << sockfd;
    incomingConnection(sockfd);
}


void PeerNodeServerRole::incomingConnection(int socketDescriptor)
{
    conn_socket = new QTcpSocket(this);
    connect(conn_socket,SIGNAL(readyRead()),this,SLOT(connSockCheckdata()));
    connect(conn_socket,SIGNAL(disconnected()),this,SLOT(connSockDisconnected()));
    conn_socket->setSocketDescriptor(socketDescriptor);
    qDebug() << "connected";
}

/// P2P文件服务器 给 客户端 发送文件
void PeerNodeServerRole::transfer(QString& filepath)
{
    QFile file(filepath);///先打开本地文件
    QFileInfo info(file);
    qint64 filesize = info.size();
    QString msg;

    if(file.open(QIODevice::ReadOnly))
    {
        char buf[257];
        msg = SUCC;

        ///发送给了“对端”
        MYLOG("send tag : %s, Preparing for body ...", msg.toStdString().c_str());
        conn_socket->write(msg.toLatin1(), msg.length());
        for(int i = 0; i < filesize / 256; ++i)
        {
            file.read(buf, 256);
            qDebug() << conn_socket->write(buf, 256);
            qDebug() << conn_socket->waitForBytesWritten(3000);
        }
        file.read(buf, filesize % 256);
        qDebug() << conn_socket->write(buf, filesize % 256);
        qDebug() <<  conn_socket->waitForBytesWritten(3000);
        MYLOG("send body over, filesize : %ld !", filesize);
    }
    else
    {
        msg = FP_ERR;
        MYLOG("send FP_ERR !");
        conn_socket->write(msg.toLatin1(), msg.length());
    }
}

